package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.BaseContext;
import com.itheima.reggie.utils.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private AddressBookMapper addressBookMapper;
    @Override
    public Result<String> createOrder(Orders orders) {
        // 查询当前用户的购物车中是否有商品
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(queryWrapper);
        // 当前用户的购物车中没有商品
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new RuntimeException("购物车为空");
        }
        // 当前购物车有商品
        // 完善订单信息
        orders.setUserId(userId);
        String orderNumber = RandomStringUtils.randomNumeric(20);
        orders.setNumber(orderNumber);
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        // 计算总价
        BigDecimal result = BigDecimal.valueOf(0);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal number = BigDecimal.valueOf(shoppingCart.getNumber());
            BigDecimal amount = shoppingCart.getAmount();
            result = result.add(number.multiply(amount));
        }
        orders.setAmount(result);
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(addressBook.getConsignee());
        orderMapper.insert(orders);
        // 加工订单详情信息
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetailMapper.insert(orderDetail);
        }
        // 清空该用户的购物车
        shoppingCartMapper.delete(queryWrapper);
        return Result.success("订单创建成功");
    }

    @Override
    public Result<Page<Orders>> getOrdersPageWithCondition(int currentPage, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(number), Orders::getNumber, number)
                .ge(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime)
                .le(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);
        orderMapper.selectPage(ordersPage, queryWrapper);
        return Result.success(ordersPage);
    }


}
